package alipay.openplatform.edu.campus.jiuye.api.controller.activity;

import alipay.openplatform.edu.campus.jiuye.api.utils.ContextUtils;
import alipay.openplatform.edu.campus.jiuye.common.cache.CacheManagerService;
import alipay.openplatform.edu.campus.jiuye.common.enums.DateEnum;
import alipay.openplatform.edu.campus.jiuye.common.enums.ResultCode;
import alipay.openplatform.edu.campus.jiuye.common.page.Page;
import alipay.openplatform.edu.campus.jiuye.common.page.PageUtil;
import alipay.openplatform.edu.campus.jiuye.common.utils.HttpUtils;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.model.vo.BllGoodVoiceVO;
import alipay.openplatform.edu.campus.jiuye.model.vo.UserBaseInfo;
import alipay.openplatform.edu.campus.jiuye.service.dao.ApiResult;
import alipay.openplatform.edu.campus.jiuye.service.iservice.activity.IBllGoodVoiceUserService;
import alipay.openplatform.edu.campus.jiuye.service.iservice.user.IUserInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangdan on 16/10/27.
 * 好声音活动
 */
@Controller
@RequestMapping(value = "/jiuye/api")
public class BllGoodVoiceUserController {

    private static Logger logger = LoggerFactory.getLogger(BllGoodVoiceUserController.class);

    @Autowired
    private IBllGoodVoiceUserService bllGoodVoiceUserService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheManagerService cacheManagerService;
    @Autowired
    private IUserInfoService userInfoService;


    @ResponseBody
    @RequestMapping(value = "/getCandidatesList", method = RequestMethod.POST)
    public ApiResult getCandidatesList(@RequestParam(value = "areaId", required = true) Integer areaId,
                                       String pageNo, String pageSize) {
        logger.info("好声音活动|BllGoodVoiceUserController|getCandidatesList|areaId={},pageNo={},pageSize={}", areaId, pageNo, pageSize);
        String uid = ContextUtils.getUserId(request);
        Map<String, Object> paramter = new HashMap<String, Object>();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        paramter.put("areaId", areaId);
        Page page = PageUtil.buidPagebean(request, paramter);
        try {
            page = bllGoodVoiceUserService.getCandidatesList(page, uid);
            int sendCount = bllGoodVoiceUserService.sendCount(uid);
            resultMap.put("page", page);
            resultMap.put("dateCount", sendCount);
            resultMap.put("ifBeforeDeadline", bllGoodVoiceUserService.ifBeforeDate(DateEnum.DEADLINE.name));
        } catch (Exception e) {
            logger.error("获取列表异常|BllGoodVoiceUserController|getCandidatesList", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), resultMap);
    }

    /**
     * 好声音活动-根据用户id查询用户详情
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserInfoById")
    public ApiResult getUserInfoById(@RequestParam(value = "id") Integer id) {
        logger.info("好声音活动|BllGoodVoiceUserController|getUserInfoById|id={}", id);
        BllGoodVoiceVO bllGoodVoiceVO = new BllGoodVoiceVO();
        try {
            String uid = ContextUtils.getUserId(request);
            int sendCount = bllGoodVoiceUserService.sendCount(uid);
            bllGoodVoiceVO = bllGoodVoiceUserService.selectByPrimaryKey(id, uid);

            bllGoodVoiceVO.setDateCount(sendCount);
        } catch (Exception e) {
            logger.error("好声音活动-获取个人信息失败|BllGoodVoiceUserController|getUserInfoById");
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), bllGoodVoiceVO);
    }


    /**
     * 投票
     *
     * @return 当前用户的投票数量
     * @id 用户的ID
     */
    @ResponseBody
    @RequestMapping(value = "/sendVote", method = RequestMethod.POST)
    public ApiResult sendVote(@RequestParam(value = "id", required = true) Integer id) {

        String uid = ContextUtils.getUserId(request);

        //String uid = "2088012199249492";
        if (id == null || id == 0 || uid == null) {
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }

        try {
            return bllGoodVoiceUserService.sendVote(id, uid);
        } catch (Exception e) {
            logger.error("好声音活动-投票|BllGoodVoiceUserController|sendVote", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }

    }


    /**
     * 获取当前用户今天的投票记录
     *
     * @uid 登陆用户的编号
     */
    @ResponseBody
    @RequestMapping(value = "/getUserSendInfoNow", method = RequestMethod.POST)
    public ApiResult getUserSendInfoNow() {
        String uid = ContextUtils.getUserId(request);

        return bllGoodVoiceUserService.getUserSendInfoNow(uid);
    }

    /**
     * 埋点
     * type:pShare,actShare
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/scanTimes")
    public ApiResult scanTimes(@RequestParam(value = "type", required = true) String type) {
        logger.info("好声音活动|BllGoodVoiceUserController|shareTimes|type={}", type);
        try {
            String uid = ContextUtils.getUserId(request);
            if (ObjectUtils.hasEmpty(uid, type)) {
                return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
            }
            bllGoodVoiceUserService.scanTimes(type);
            return ApiResult.build(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName());
        } catch (Exception e) {
            logger.error("好声音活动-个人页/活动分享|BllGoodVoiceUserController|shareTimes", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
    }

    /**
     * 流量宝、流量来了跳转
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/flowUrl")
    public ApiResult flowUrl() {
        String userId = ContextUtils.getUserId(request);
        try {
            UserBaseInfo userBaseInfo = userInfoService.getUserInfoByUserId(userId);
            String mobile = userBaseInfo.getMobile();
            if (StringUtils.isBlank(mobile)) {
                return ApiResult.build("-10000", "手机号码为空,产品聚合页直接不显示该权益");
            } else {
                return bdHandleFlowUrl(mobile);
            }
        } catch (Exception e) {
            logger.error("好声音活动|流量宝、流量来了跳转|系统异常");
            return ApiResult.build(ResultCode.SYSTEM_EXCEIPTION.getCode(), ResultCode.SYSTEM_EXCEIPTION.getName());
        }
    }

    /**
     * 百度归属地查询
     *
     * @param mobile
     * @return
     */
    private ApiResult bdHandleFlowUrl(String mobile) {
        Map map = new HashMap();
        map.put("resource_name", "guishudi");
        map.put("query", mobile);
        String result =
                HttpUtils.getDataAsString("https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php", map, 3000);
        GuiShudi guiShudi = JSON.parseObject(result, GuiShudi.class);
        List<GuiShudi.DataBean> list = guiShudi.getData();
        if (list.size() > 0) {
            GuiShudi.DataBean dataBean = list.get(0);
            //获取运营商类型
            String type = dataBean.getType();
            if (!type.equals("中国电信")) {
                //电信虚拟运营商
                if (mobile.startsWith("1700") || mobile.startsWith("1701") || mobile.startsWith("1702")) {
                    return handleUrl(dataBean);
                } else {
                    return ApiResult.build("-10000", "省份、运营商不存在或者运营商不是中国电信,产品聚合页直接不显示该权益");
                }
            }
            return handleUrl(dataBean);
        } else {
            return ApiResult.build("-10000", "手机号码不合法,产品聚合页直接不显示该权益");
        }

    }

    private ApiResult handleUrl(GuiShudi.DataBean dataBean) {
        String province = dataBean.getProv();
        String city = dataBean.getCity();
        Map p2pmap = province2product();
        String product = p2pmap.get(province) == null ? p2pmap.get(city) == null ? "" : p2pmap.get(city).toString() : p2pmap.get(province).toString();
        if (product.equals("llb")) {
            logger.info("好声音活动|返回流量宝链接");
            return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), "http://nb.189.cn/webapp/zt/sendflow/index.html");
        } else if (product.equals("llll")) {
            logger.info("好声音活动|返回流量来了链接");
            return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), "http://win.800.189.cn/wxpublic/jsp/partnerActivity/Alipay_flowCome.jsp");
        } else {
            return ApiResult.build("-10000", "手机号码对应省份不在此处活动范围,产品聚合页直接不显示该权益");
        }
    }

//    /**
//     * 淘宝归属地查询
//     *
//     * @param mobile
//     * @return
//     */
//    private ApiResult tbHandleFlowUrl(String mobile) {
//        Map map = new HashMap();
//        map.put("tel", mobile);
//        String result =
//                HttpUtils.getDataAsString("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm", map, 3000);
//        result = result.replaceAll(" ", "").replace("__GetZoneResult_=", "");
//        map = JSON.parseObject(result, HashMap.class);
//        Object province = map.get("province");
//        Object catName = map.get("catName");
//        if (ObjectUtils.hasEmpty(province, catName) || !catName.equals("中国电信")) {
//            return ApiResult.build("-10000", "省份、运营商不存在或者运营商不是中国电信,产品聚合页直接不显示该权益");
//        } else {
//            Map p2pmap = province2product();
//            String product = p2pmap.get(province) == null ? "" : p2pmap.get(province).toString();
//            if (product.equals("llb")) {
//                logger.info("好声音活动|返回流量宝链接");
//                return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), "待定");
//            } else if (product.equals("llll")) {
//                logger.info("好声音活动|返回流量来了链接");
//                return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), "http://118.123.170.72/wx/jsp/partnerActivity/Alipay_flowCome.jsp");
//            } else {
//                return ApiResult.build("-10000", "手机号码对应省份不在此处活动范围,产品聚合页直接不显示该权益");
//            }
//        }
//    }

    private static Map<String, Object> province2product() {
        Map<String, Object> map = new HashedMap();
        map.put("北京", "llb");
        map.put("河北", "llb");
        map.put("河南", "llb");
        map.put("黑龙江", "llb");
        map.put("辽宁", "llb");
        map.put("内蒙古", "llb");
        map.put("宁夏", "llb");
        map.put("天津", "llb");
        map.put("江西", "llb");
        map.put("吉林", "llb");
        map.put("江苏", "llb");
        map.put("广东", "llb");
        map.put("海南", "llb");
        map.put("贵州", "llb");
        map.put("山东", "llll");
        map.put("山西", "llll");
        map.put("青海", "llll");
        map.put("西藏", "llll");
        map.put("新疆", "llll");
        map.put("重庆", "llll");
        map.put("陕西", "llll");
        map.put("安徽", "llll");
        map.put("福建", "llll");
        map.put("广西", "llll");
        return map;
    }

}

class GuiShudi {
    private String status;
    private String t;
    private String set_cache_time;
    private List<DataBean> data;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getT() {
        return t;
    }

    public void setT(String t) {
        this.t = t;
    }

    public String getSet_cache_time() {
        return set_cache_time;
    }

    public void setSet_cache_time(String set_cache_time) {
        this.set_cache_time = set_cache_time;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private int StdStg;
        private int StdStl;
        private String _update_time;
        private String loc;
        private String key;
        private String url;
        private String title;
        private String showurl;
        private String prov;
        private String city;
        private String type;
        private int SiteId;
        private int _version;
        private int _select_time;
        private String querytype;
        private String phoneinfo;
        private String phoneno;
        private String origphoneno;
        private String titlecont;
        private String showlamp;
        private String clickneed;
        private String ExtendedLocation;
        private String OriginQuery;
        private String tplt;
        private String resourceid;
        private String fetchkey;
        private String appinfo;
        private int role_id;
        private int disp_type;

        public int getStdStg() {
            return StdStg;
        }

        public void setStdStg(int StdStg) {
            this.StdStg = StdStg;
        }

        public int getStdStl() {
            return StdStl;
        }

        public void setStdStl(int StdStl) {
            this.StdStl = StdStl;
        }

        public String get_update_time() {
            return _update_time;
        }

        public void set_update_time(String _update_time) {
            this._update_time = _update_time;
        }

        public String getLoc() {
            return loc;
        }

        public void setLoc(String loc) {
            this.loc = loc;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getShowurl() {
            return showurl;
        }

        public void setShowurl(String showurl) {
            this.showurl = showurl;
        }

        public String getProv() {
            return prov;
        }

        public void setProv(String prov) {
            this.prov = prov;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public int getSiteId() {
            return SiteId;
        }

        public void setSiteId(int SiteId) {
            this.SiteId = SiteId;
        }

        public int get_version() {
            return _version;
        }

        public void set_version(int _version) {
            this._version = _version;
        }

        public int get_select_time() {
            return _select_time;
        }

        public void set_select_time(int _select_time) {
            this._select_time = _select_time;
        }

        public String getQuerytype() {
            return querytype;
        }

        public void setQuerytype(String querytype) {
            this.querytype = querytype;
        }

        public String getPhoneinfo() {
            return phoneinfo;
        }

        public void setPhoneinfo(String phoneinfo) {
            this.phoneinfo = phoneinfo;
        }

        public String getPhoneno() {
            return phoneno;
        }

        public void setPhoneno(String phoneno) {
            this.phoneno = phoneno;
        }

        public String getOrigphoneno() {
            return origphoneno;
        }

        public void setOrigphoneno(String origphoneno) {
            this.origphoneno = origphoneno;
        }

        public String getTitlecont() {
            return titlecont;
        }

        public void setTitlecont(String titlecont) {
            this.titlecont = titlecont;
        }

        public String getShowlamp() {
            return showlamp;
        }

        public void setShowlamp(String showlamp) {
            this.showlamp = showlamp;
        }

        public String getClickneed() {
            return clickneed;
        }

        public void setClickneed(String clickneed) {
            this.clickneed = clickneed;
        }

        public String getExtendedLocation() {
            return ExtendedLocation;
        }

        public void setExtendedLocation(String ExtendedLocation) {
            this.ExtendedLocation = ExtendedLocation;
        }

        public String getOriginQuery() {
            return OriginQuery;
        }

        public void setOriginQuery(String OriginQuery) {
            this.OriginQuery = OriginQuery;
        }

        public String getTplt() {
            return tplt;
        }

        public void setTplt(String tplt) {
            this.tplt = tplt;
        }

        public String getResourceid() {
            return resourceid;
        }

        public void setResourceid(String resourceid) {
            this.resourceid = resourceid;
        }

        public String getFetchkey() {
            return fetchkey;
        }

        public void setFetchkey(String fetchkey) {
            this.fetchkey = fetchkey;
        }

        public String getAppinfo() {
            return appinfo;
        }

        public void setAppinfo(String appinfo) {
            this.appinfo = appinfo;
        }

        public int getRole_id() {
            return role_id;
        }

        public void setRole_id(int role_id) {
            this.role_id = role_id;
        }

        public int getDisp_type() {
            return disp_type;
        }

        public void setDisp_type(int disp_type) {
            this.disp_type = disp_type;
        }
    }
}
